package org.yan.kangaroo.storage.service.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;
import org.yan.kangaroo.common.util.McpStringUtils;
import org.yan.kangaroo.storage.config.QcloudConfig;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.InputStream;
import java.util.Date;

/**
 * @author wangx
 * @date 11/08/2019 10:58
 */
@Component
@Slf4j
public class CosObjectResourceClient {
    private final QcloudConfig qcloudConfig;

    private COSClient cosClient;

    public CosObjectResourceClient(QcloudConfig qcloudConfig) {
        this.qcloudConfig = qcloudConfig;
    }


    @PostConstruct
    private void initCosClient() {
        if (cosClient == null) {
            COSCredentials credentials = new BasicCOSCredentials(qcloudConfig.getSecretId(), qcloudConfig.getSecretKey());
            Region region = new Region(qcloudConfig.getRegion());
            ClientConfig clientConfig = new ClientConfig(region);
            cosClient = new COSClient(credentials, clientConfig);
        }
    }

    public String uploadFile(File file) {
        Date now = new Date();
        String date = DateFormatUtils.format(now, "yyyy-MM-dd");
        String key = date + File.separator + file.getName();
        PutObjectRequest putObjectRequest = new PutObjectRequest(qcloudConfig.getBucket(), key, file);
        PutObjectResult result = cosClient.putObject(putObjectRequest);
        log.info("[uploadFile] result:{}", result);
        return key;
    }

    public String uploadFile(InputStream inputStream, String fileName, String contentType) {
        Date now = new Date();
        String date = DateFormatUtils.format(now, "yyyy-MM-dd");
        String key = date + File.separator + McpStringUtils.getUuid() + "-" + fileName;
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(contentType);
        PutObjectResult result = cosClient.putObject(qcloudConfig.getBucket(), key, inputStream, metadata);
        log.info("[uploadFile] result:{}", result);
        return key;
    }

    public InputStream getFile(String key) {
        COSObject cosObject = cosClient.getObject(qcloudConfig.getBucket(), key);
        return cosObject.getObjectContent();
    }

}
